package com.oracle.zebrafreelytraveling.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResCircle;
import com.oracle.zebrafreelytraveling.net.Api;
import com.oracle.zebrafreelytraveling.net.HttpManager;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.CommonAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.MultiItemTypeAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.base.ViewHolder;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.wrapper.LoadMoreWrapper;
import com.oracle.zebrafreelytraveling.ui.CircleIntroActivity;
import com.oracle.zebrafreelytraveling.ui.adapter.CircleListAdapter;
import com.oracle.zebrafreelytraveling.utils.StringUtil;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;
import com.oracle.zebrafreelytraveling.utils.ToastUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by yydcnjjw on 2017/7/20.
 */

public class ChatRingFragment extends Fragment {

    private View mView;
    private RecyclerView mChatCircleRecycleView;
    private List<ResCircle.DataBean> mChatCircleList;
    private CommonAdapter<ResCircle.DataBean> mChatCircleAdapter;
    private LoadMoreWrapper mLoadMoreWrapper;
    private ViewHolder mViewHolder;
    private SimpleDraweeView mCircleImage;

    private SwipeRefreshLayout mCharCircleRefreshLayout;

    private int page = 0;
    private String currentCity;
    private Disposable mDisposable;

    private boolean isListNull = false;
    private boolean isFinish = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mChatCircleList.size() == 0) {
            page = 0;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_chat_ring, container, false);
        initView();
        initCircleRecycleList();
        isFinish = true;
        return mView;
    }

    private void initView() {
        mCharCircleRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.char_ring_refresh);
        mCharCircleRefreshLayout.setOnRefreshListener(() -> {
            mCharCircleRefreshLayout.setRefreshing(true);
            if (!TextUtils.isEmpty(currentCity)) {
                getCircleList(Constant.GET_DATA_TYPE_NOMAL, Constant.RES_CITY);
            } else {
                getCircleList(Constant.GET_DATA_TYPE_NOMAL, Constant.RES_COUNTRY);
            }
            page++;
        });
        mChatCircleRecycleView = (RecyclerView) mView.findViewById(R.id.chat_group_recycle_view);
    }

    private void initCircleRecycleList() {
        mChatCircleRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mChatCircleList = new ArrayList<>();
        mChatCircleAdapter = new CircleListAdapter(getActivity(), R.layout.item_chat_circle, mChatCircleList);
        mChatCircleAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                //TODO 圈子的详细信息 包括 用户列表等
                ResCircle.DataBean dataBean = mChatCircleList.get(position);
                CircleIntroActivity.startCircleIntroActivity(getActivity(), dataBean);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return true;
            }
        });
        mLoadMoreWrapper = new LoadMoreWrapper(mChatCircleAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.footer_loading);
        mLoadMoreWrapper.setOnLoadMoreListener(viewHolder -> {
            mViewHolder = viewHolder;
            if (!isListNull) {
                if (!TextUtils.isEmpty(currentCity)) {
                    getCircleList(Constant.GET_DATA_TYPE_LOADMORE, Constant.RES_CITY);
                } else {
                    getCircleList(Constant.GET_DATA_TYPE_LOADMORE, Constant.RES_COUNTRY);
                }
            } else {
                viewHolder.getConvertView().setVisibility(View.GONE);
            }

        });
        mChatCircleRecycleView.setAdapter(mLoadMoreWrapper);
    }

    private void getCircleList(int type, int resType) {
        Api api = HttpManager.getInstance().getService(Constant.BASE_URL);
        Observable<ResCircle> observable = null;
        if (resType == Constant.RES_CITY) {
            observable = api.getCircleListFromCity(currentCity, page, Constant.MAX_PAGE);
        } else {
            observable = api.getCircleListFromCountry(page, Constant.MAX_PAGE);
        }
        if (observable == null) {
            return;
        }
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResCircle>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull ResCircle resCircle) {
                        if (mChatCircleList == null) {
                            return;
                        }
                        if (resCircle.getCode().equals(Constant.REQUEST_SUCCESS)) {
                            if (type == Constant.GET_DATA_TYPE_NOMAL) {
                                mChatCircleList.clear();
                            }
                            mChatCircleList.addAll(resCircle.getData());
                            isListNull = false;
                        } else {
                            ToastUtil.showToast(resCircle.getMessage());
                            isListNull = true;
                            page = 0;
                            mViewHolder.getConvertView().setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("chatRingerror", e.getMessage());
                        if (mCharCircleRefreshLayout == null) {
                            return;
                        }
                        mCharCircleRefreshLayout.setRefreshing(false);
                        mViewHolder.getConvertView().setVisibility(View.GONE);
                    }

                    @Override
                    public void onComplete() {
                        if (mCharCircleRefreshLayout == null) {
                            return;
                        }
                        mCharCircleRefreshLayout.setRefreshing(false);
                        if (mViewHolder != null) {
                            mViewHolder.getConvertView().setVisibility(View.GONE);
                        }
                        if (mLoadMoreWrapper != null) {
                            mLoadMoreWrapper.notifyDataSetChanged();
                        }

                    }
                });
        page++;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        page = 0;
    }

    public void setCurrentCity(String city) {
        currentCity = city;
        if (isFinish){
            getCircleList(Constant.GET_DATA_TYPE_NOMAL, Constant.RES_CITY);
        }

    }
}
